package com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.lmm.dresswisdom.lmmframe.reactnative.BasePlugin;
import com.lmm.dresswisdom.lmmframe.reactnative.annotation.RNPlugin;
import com.lmm.lcbusiness.lcbusiness.dbmodel.GoodsCategoryRealm;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.ReactNativeActivity;
import com.lmm.lcbusiness.lcbusiness.utils.RealmUtils;

import java.util.Map;

import io.realm.RealmResults;

/**
 * @author xmgong
 * @date 2017/12/4
 * 获取商品栏目
 */
@RNPlugin(method = "getGoodsCategory")
public class GetGoodsCategoryPlugin extends BasePlugin<ReactNativeActivity> {
    public GetGoodsCategoryPlugin(ReactNativeActivity act) {
        super(act);
    }

    @Override
    protected void doAction(Map<String, Object> map, Callback callback) {
        if (map.containsKey("code")) {
            //取详情
            String code = map.get("code").toString();
            GoodsCategoryRealm categoryRealm = RealmUtils.getRealm().where(GoodsCategoryRealm.class).equalTo("catCode", code).findFirst();
            callback.invoke(getMap(categoryRealm));
        } else if (map.containsKey("parentId")) {
            int id = Integer.parseInt(map.get("parentId").toString());
            RealmResults<GoodsCategoryRealm> res = RealmUtils.getRealm().where(GoodsCategoryRealm.class).equalTo("parentId", id).findAll();
            WritableArray list = Arguments.createArray();
            for (GoodsCategoryRealm item : res) {
                list.pushMap(getMap(item));
            }
            WritableMap resmap = Arguments.createMap();
            resmap.putArray("list", list);
            callback.invoke(resmap);
        }
    }

    private WritableMap getMap(GoodsCategoryRealm category) {
        WritableMap item = Arguments.createMap();
        item.putString("catName", category.getCatName());
        item.putString("catCode", category.getCatCode());
        item.putInt("catIndex", category.getCatIndex());
        item.putInt("enable", category.getEnable());
        item.putInt("isType", category.getIsType());
        item.putInt("parentId", category.getParentId());
        item.putInt("sort", category.getSort());
        item.putInt("catId", category.getCatId());
        return item;
    }

}
